package com.huaqin.excel.handler;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;

import com.huaqin.excel.beans.ContentBean;
import com.huaqin.excel.handler.ExcelDataSource.CHECKLIST_TYPE;
import com.huaqin.excel.util.InternationalUtils;

/**
 * @author guojianhui handler data from checklist origin data
 */
public class ExcelDataHandler {

	private static ExcelDataHandler instance = null;

	private static final String CLIENT_ID_GMS_PERF = "[ro.com.google.clientidbase";

	private static final String CLIENT_ID_GMS_PERF1 = "ro.com.google.clientidbase";

	private static final String DF_SYSTEM_PERF = "/system";
	private static final String DF_DATA_PERF = "/data";
	private static final String DF_CACHE_PERF = "/cache";

	private/* static */HashMap<String, String> mPropMap = null;

	private String[] fingerprintEntryKey = { "BRAND", "PRODUCT", "DEVICE",
			"VERSION.RELEASE", "ID", "VERSION.INCREMENTAL", "TYPE", "TAGS" };

	private Map<String, String> mFingerPrinterMap = null;

	private Map<String, String> mClientIdMap = null;

	/* static */StringBuilder mDFs = null;
	StringBuilder mClientIds = null;
	StringBuffer appsInfos = new StringBuffer();
	
	private String mPropValue = null;

	private ExcelDataHandler() {
		mDFs = new StringBuilder();
		mClientIds = new StringBuilder();
		mPropMap = new HashMap<String, String>();
		mClientIdMap = new HashMap<String, String>();
	}

	/**
	 * sington instance
	 * 
	 * @return
	 * @author guojianhui
	 */
	public static ExcelDataHandler getInstance() {

		if (instance == null) {
			instance = new ExcelDataHandler();
		}

		return instance;
	}
	
	/**
	 * gc free memory
	 */
	public void free() {
		instance = null;
	}

	public/* static */void formatString(String str, CHECKLIST_TYPE type) {
		switch (type) {
		case FINGERPRINT:
			formatFingerPrintToHashMap(str);
			break;
		case PROP:
			formatPropToHashMap(str);
			break;
		case LOCAL:
		case BRAND:
		case DF:
			formatDF(str);
			break;
		case CLIENTID:
			formatClientId(str);
			break;
		default:
			break;
		}
	}

	/**
	 * conert string to hashmap
	 * 
	 * @param prop
	 * @author guojianhui
	 * @throws Exception
	 */
	public/* static */void formatPropToHashMap(String prop) {

		String getprop = prop;

		if (getprop == null) {
			getprop = "";
		}

		try {

			String re1 = "(\\[.*?\\])"; // Square Braces 1
			String re2 = ".*?"; // Non-greedy match on filler
			String re3 = "(\\[.*?\\])"; // Square Braces 2

			Pattern p = Pattern.compile(re1 + re2 + re3);
			Matcher m = p.matcher(getprop.trim());
			if (m.find()) {
				int keyLength = m.group(1).trim().length();
				int valueLength = m.group(2).trim().length();

				String propKey = m.group(1).trim().substring(1, keyLength - 1);
				String propValue = m.group(2).trim()
						.substring(1, valueLength - 1);

				mPropMap.put(propKey, propValue);
				formatClientIdMap(propKey, propValue);
//				System.out.print("guo(" + propKey.toString() + ")" + "("
//						+ propValue.toString() + ")" + "\n");
			}

		} catch (Exception e) {
			e.printStackTrace();
			try {
				throw new Exception("out of index!!!");
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

	}

	public void formatClientIdMap(String key, String value) {
		if (key == null || value == null) {
			return;
		}
//		System.out.println("formatClientIdMap, value: " + value);
		if (key.startsWith(CLIENT_ID_GMS_PERF1)) {
//			System.out.println("formatClientIdMap, value: " + value);
			mClientIdMap.put(key, value);
		}
	}

	/*
	 * match is internal product
	 * 
	 * @param product
	 * 
	 * @return boolean
	 */
	public boolean isSpecialCarrier() {

		Iterator iter = mClientIdMap.entrySet().iterator();
		int flag = 0x000001;

		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String val = (String) entry.getValue();
//			System.out.println(val);

			if (val != null && val.matches(ExcelConstants.ANDROID_HAWEI)) {
				// flag |= CLIENTID_BASE;
				flag = (flag << 1);
			}
		}
//		System.out.println("isSpecialCarrier1, flag: " + flag);
		if (flag == 32) {
//			System.out.println("isSpecialCarrier2, flag: " + flag);
			return false;
		}

		return true;

	}

	public String getSpecialCarrier() {
		if (isSpecialCarrier()) {

			return InternationalUtils
					.getStringFromProperties("Special_Operator");

		}

		return InternationalUtils.getStringFromProperties("Common_Operator");

	}

	/**
	 * format fingerprinter to hashmap
	 * 
	 * @param str
	 * @author taojin
	 */
	public void formatFingerPrintToHashMap(String str) {

		String str1 = str;

		if (str1 == null) {
			str1 = "";
		}

		int SPLIT_NUM = 8;
		String[] fingerPrint = str1.split("/|:", SPLIT_NUM);

		for (int i = 0; i < fingerPrint.length; i++) {
			mFingerPrinterMap.put(fingerprintEntryKey[i], fingerPrint[i]);
			// System.out.println(fingerprintkey[i]+ ":" +fingerPrint[i]);
		}

		Set<String> set = mFingerPrinterMap.keySet();
		Iterator<String> it = set.iterator();
		while (it.hasNext()) {
			String str2 = (String) it.next();
			String str3 = (String) mFingerPrinterMap.get(str2);
//			System.out.println(str2 + ":" + str3);
		}
	}

	/**
	 * get prop by key (hashmap get)
	 * 
	 * @param key
	 * @return
	 * @author guojianhui
	 */
	public/* static */String getPropHashMap(String key) {

		return mPropMap.get(key);
	}

	/**
	 * clear getprop hashmap
	 * 
	 * @author guojianhui
	 */
	public void clearPropHashMap() {
		mPropMap.clear();
	}

	/**
	 * format df data source
	 * 
	 * @param df
	 * @author guojianhui
	 */
	public/* static */void formatDF(String df) {

		String mDF = df;

		if (mDF == null) {
			mDF = "";
		}

		if (df.startsWith(DF_SYSTEM_PERF)) {
			mDFs.append(formatWithG(mDF) + "\r\n");
		} else if (df.startsWith(DF_DATA_PERF)) {
			mDFs.append(formatWithG(mDF) + "\r\n");
		} else if (df.startsWith(DF_CACHE_PERF)) {
			mDFs.append(formatWithM(mDF) + "\r\n");
		}

//		System.out.print(mDFs + "\n");
	}

	private String formatWithG(String mDF){
		int i = mDF.indexOf('G');
		String df = mDF.substring(0,i+1);
		return df;
	}

	private String formatWithM(String mDF){
		int i = mDF.indexOf('M');
		String df = mDF.substring(0,i+1);
		return df;
	}

	/**
	 * get df data
	 * 
	 * @return
	 */
	public String getDFString() {
		return mDFs.toString();
	}

	/**
	 * get cliend id
	 * 
	 * @author guojianhui
	 */
	public void formatClientId(String clientId) {

		String mClientId = clientId;

		if (mClientId == null) {
			mClientId = "";
		}

		if (mClientId.trim().startsWith(CLIENT_ID_GMS_PERF)) {
			mClientIds.append(mClientId + "\r\n");
		}
	}

	/**
	 * get df data
	 * 
	 * @return
	 * @author guojianhui
	 */
	public String getClientIdString() {
//		System.out.print("getClientIdString:" + mClientIds.toString() + "\n");
		return mClientIds.toString();
	}

	//GmsAppInfos not updating here
	
	// /**read gms apk info
	// * @param Template
	// * @param sheetx
	// * @return
	// * @author zhongshengbin
	// */
	// public void formatGmsPackageInfo(String Template, int sheetx) {
	//
	//
	// ExcelReadAndWrite handler = new ExcelReadAndWrite();
	// handler.loadTemplate(Template, 0);
	// // read excel source data
	// for (int i = 3; i < 40; i++) {
	// String appName = null;
	// String appVersion = null;
	// String appInfo = null;
	// appName = handler.readInCell(i, 0);
	// appVersion = handler.readInCell(i, 5);
	// appInfo = appName + " " + appVersion + "\r\n";
	// if (null == appName || null == appVersion) {
	// continue;
	// }
	// appsInfos.append(appInfo);
	// }
	//
	// }

	/**
	 * get df data
	 * 
	 * @return
	 * @author guojianhui
	 */
	public String getGMSApkInfoString() {
//		System.out.print("getGMSApkInfoString:" + appsInfos.toString() + "\n");
		return appsInfos.toString();
	}
	
	
	public String getFileDirName() {
		
		String finalDirName = null;
		String[] versionfirst = getPropHashMap("ro.build.version.incremental").split("B");		
		String[] versionsecond = getPropHashMap("ro.build.display.id").split("B");
		
		if(versionfirst[1].equals(versionsecond[1])){
			//judge and set different folder by display and huawei incremental version 
			finalDirName = getPropHashMap("ro.product.name") + "_" + ContentBean.getInstance().getCountry()+ ContentBean.getInstance().getOperator()
					+ "_" + getPropHashMap("ro.build.version.incremental");
			
		}else{
			finalDirName = getPropHashMap("ro.product.name") + "_" + ContentBean.getInstance().getCountry()+ ContentBean.getInstance().getOperator()
					 + versionfirst[0] + "B" + versionsecond[1] + "_B" + versionfirst[1];
		}
		
		return finalDirName;
	}
	
	
	/**
	 * get prop from devices 
	 * @param cmd
	 * @param type
	 * @author guojianhui
	 */
	
	public String getPropValue() {
		
		return mPropValue;
	}
	
	public void exePropValue(String cmd) {
		
//		final String line;
		try {

			Process process = Runtime.getRuntime().exec(cmd);
			final BufferedWriter outputStream = new BufferedWriter(
					new OutputStreamWriter(process.getOutputStream()));
			final BufferedReader inputStream = new BufferedReader(
					new InputStreamReader(process.getInputStream()));

			

			final BufferedReader errorReader = new BufferedReader(
					new InputStreamReader(process.getErrorStream()));

			new Thread(new Runnable() {

				public void run() {
					String line = null;
//					System.out.println("listener started");
					try {

						while ((line = inputStream.readLine()) != null) {
							if(!line.trim().equals("")) {
//								System.out.println("get hq version:"+line);
								mPropValue = line;
							}
							
						}

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

			}).start();

			/*new Thread(new Runnable() {
				final BufferedReader br = new BufferedReader(
						new InputStreamReader(System.in));

				public void run() {
					System.out.println("writer started");

					String line;

					try {
						while ((line = br.readLine()) != null) {

							outputStream.write(line + "\r\n");
							outputStream.flush();

						}

					} catch (IOException e) {
						e.printStackTrace();
					}

				}

			}).start();*/

			int i = process.waitFor();
//			System.out.println("i=" + i);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	


}
